package com.hdcircles.autoform.ui.label.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.hdcircles.autoform.R;
import com.hdcircles.autoform.app.Constants;
import com.hdcircles.autoform.base.BaseActivity;
import com.hdcircles.autoform.model.bean.ChooseQuestionBean;
import com.hdcircles.autoform.model.bean.FormBean;
import com.hdcircles.autoform.model.bean.QuestionBean;
import com.hdcircles.autoform.model.bean.User;
import com.hdcircles.autoform.model.bean.UserFormBean;
import com.hdcircles.autoform.presenter.UserListPresenter;
import com.hdcircles.autoform.presenter.contract.UserListContract;
import com.hdcircles.autoform.ui.label.adapter.UserListAdapter;
import com.hdcircles.autoform.util.SharedPreferenceUtil;
import com.hdcircles.autoform.util.SnackbarUtil;
import com.hdcircles.autoform.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;

/**
 * Created by hdcircles on 2016/11/18.
 */

public class UserListActivity extends BaseActivity<UserListPresenter> implements UserListContract.View {


    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rv_user)
    RecyclerView rvUser;
    @BindView(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;

    private UserListAdapter adapter;

    private FormBean formBean;

    private FormBean mForm;
    private ProgressDialog progressDialog;
    private Snackbar snackbar;

    private List<User> mUserList;

    private List<User> selectUser;

    private boolean isAllChecked;

    private MenuItem selectItem;

    private List<QuestionBean> mQuestionList;

    private boolean isShare;


    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_user_list;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.user_list_menu, menu);
        selectItem = menu.findItem(R.id.action_select);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_select) {
            //TODO allCheck
            if (null != adapter && null != mUserList) {
                if (!isAllChecked) {
                    for (User user : mUserList) {
                        user.setSelected(true);
                        selectUser.add(user);
                        HashSet hashSet = new HashSet(selectUser);
                        selectUser.clear();
                        selectUser.addAll(hashSet);
                        adapter.notifyDataSetChanged();
                    }
                    isAllChecked = true;
                    item.setTitle("全不选");
                    snackbar.setText("已选择" + selectUser.size() + "名用户");
                    snackbar.show();
                } else {
                    for (User user : mUserList) {
                        //TODO
                        if (!user.isShared()) {
                            user.setSelected(false);
                            selectUser.remove(user);
                        }
                        adapter.notifyDataSetChanged();
                    }
                    isAllChecked = false;
                    item.setTitle("全选");
                    snackbar.dismiss();
                }

            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void initEventAndData() {
        setToolBar(toolbar, "选择用户");
        Intent intent = getIntent();
        formBean = intent.getParcelableExtra("form");
        isShare = intent.getBooleanExtra("isShare", false);
        adapter = new UserListAdapter();
        selectUser = adapter.getSelectedUser();
        rvUser.setLayoutManager(new LinearLayoutManager(this));
        rvUser.setAdapter(adapter);
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(true);
                mPresenter.getUsers();
                if (!isShare)
                    mPresenter.getQuestion(formBean.getId());
            }
        });
        snackbar = Snackbar.make(toolbar, "已选择0名用户", Snackbar.LENGTH_INDEFINITE);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (null == mUserList) {
                    mPresenter.getUsers();
                    return;
                }
                refreshLayout.setRefreshing(false);
            }
        });
        adapter.setOnItemClickListener(new UserListAdapter.onItemClickListener() {
            @Override
            public void onItemClick(User user) {

                if (isAllChecked) {
                    selectItem.setTitle("全选");
                    isAllChecked = false;
                }
                if (user.isSelected()) {
                    user.setSelected(false);
                    selectUser.remove(user);
                } else {
                    user.setSelected(true);
                    selectUser.add(user);
                }
                adapter.notifyDataSetChanged();
                snackbar.setText("已选择" + selectUser.size() + "名用户");
                snackbar.show();
            }
        });
        String msg = isShare ? "共享" : "发送";
        snackbar.setAction(msg, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showProgress();
                if (isShare) {
                    List<String> userEmailList = new ArrayList<>();
                    for (User user : selectUser) {
                        if (!user.isShared())
                            userEmailList.add(user.getEmail());
                    }
                    //TODO share form
                    mPresenter.shareForm(formBean.getId(), userEmailList);
                    return;
                }
                User user = selectUser.get(0);
                mForm = new FormBean();
                mForm.setCreator(SharedPreferenceUtil.getUserEmail());
                mForm.setFormId(formBean.getFormId());
                mForm.setFormName(formBean.getFormName());
                mForm.setReceiver(user.getEmail());
                mForm.setStatus(Constants.STATUS_UNDONE);
                mForm.setTime(System.currentTimeMillis());
                mForm.setQuestion(mQuestionList);
                mPresenter.send2User(mForm, 0);

            }
        });
    }

    @Override
    public void ShowUserList(List<User> userList) {

        for (Iterator<User> iterator = userList.iterator(); iterator.hasNext(); ) {
            User u = iterator.next();
            if (u.getEmail().equals(SharedPreferenceUtil.getUserEmail())) {
                iterator.remove();
            }
        }
        mUserList = userList;
        if (isShare) {
            List<UserFormBean> user_formList = formBean.getUser_Form();
            if (null != user_formList) {
                HashMap<String, User> map = new HashMap<>();
                for (User user : userList) {
                    map.put(user.getEmail(), user);
                }
                List<User> users=new ArrayList<>();
                for (UserFormBean userFormBean : user_formList) {
                    User user = map.get(userFormBean.getEmail());
                    if (null != user) {
                        user.setSelected(true);
                        user.setShared(true);
                        selectUser.add(user);
                        userList.remove(user);
                        users.add(user);
                    }
                }
                users.addAll(userList);
                userList=users;
            }
        }
        adapter.setUsers(userList);
        adapter.notifyDataSetChanged();
        refreshLayout.setRefreshing(false);
    }

    @Override
    public void getQuestion(final List<QuestionBean> questionList) {
        for (QuestionBean questionBean : questionList) {
            if (questionBean.getType() == Constants.TYPE_MULTIPLE_CHOOSE || questionBean.getType() == Constants.TYPE_SINGLE_CHOOSE) {
                mPresenter.getChoose(questionBean);
            }
            questionBean.setId(null);
        }
        mQuestionList = questionList;


    }

    @Override
    public void setQuestion(List<QuestionBean> questionList) {

    }

    @Override
    public void sendSuccess(final String msg, int index) {
//        mPresenter.updateInitForm(formBean.getId(),formBean.getShared());
        index++;
        if (index < selectUser.size()) {
            User user = selectUser.get(index);
            mForm = new FormBean();
            mForm.setCreator(SharedPreferenceUtil.getUserEmail());
            mForm.setFormId(formBean.getFormId());
            mForm.setFormName(formBean.getFormName());
            mForm.setReceiver(user.getEmail());
            mForm.setStatus(Constants.STATUS_UNDONE);
            mForm.setTime(System.currentTimeMillis());
            mForm.setQuestion(mQuestionList);
            mPresenter.send2User(mForm, index);
        }

        if (index == selectUser.size() - 1 || selectUser.size() == 1) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    closeProgress();
                    ToastUtil.shortShow(msg);
                    finish();
                }
            }, 3000);

        }
    }

    @Override
    public void updateSuccess(String msg) {
        closeProgress();
        ToastUtil.shortShow(msg);
        finish();
    }

    @Override
    public void shareSuccess(String msg) {
        closeProgress();
        ToastUtil.shortShow(msg);
        finish();
    }

    @Override
    public void showError(String msg) {
        SnackbarUtil.showShort(toolbar, msg);
    }

    private void showProgress() {
        progressDialog = new ProgressDialog(this, R.style.AppTheme_Dark_Dialog);
        progressDialog.setMessage("正在发送");
        progressDialog.setIndeterminate(false);
        progressDialog.show();
    }

    private void closeProgress() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

}
